<template>
    <el-row>
      <el-col :span="24">
        <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
                 style="width: 400px; margin-left:50px;">
          <el-form-item label="标题" prop="title">
            <el-input v-model="dataForm.title"/>
          </el-form-item>
          <el-form-item label="文旅" prop="graphicType">
            <el-radio-group v-model="dataForm.graphicType">
              <el-radio-button v-for="(type,index) in types" :label="index">{{type}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="图片" prop="graphicType" style="width: 700px;">
            <el-upload
              style="width: 500px;"
              :headers="headers"
              :action="uploadPath"
              list-type="picture-card"
              :file-list="dataForm.link"
              :on-success="uploadUrl"
              :before-upload="checkFileSize"
              multiple
              :limit="9"
              accept=".jpg,.jpeg,.png,.gif,.mp4">
              <i slot="default" class="el-icon-plus"/>
              <div slot="file" slot-scope="{file}" style="height: 100%">
                <img v-if="!endWith(file.url,'.mp4')" class="el-upload-list__item-thumbnail" :src="file.url">
                <video v-else :id="'video-'+file.url" controls="controls" style="height: 85%" class="el-upload-list__item-thumbnail"  preload="metadata">
                  <source :src="file.url" type="video/mp4">
                </video>
                <!--              <img v-if="endWith(file.url,'.mp4')" class="el-upload-list__item-thumbnail" :src="getVideoFirstImg(file.url)">-->
                <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in" />
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete" />
                </span>
              </span>
              </div>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/mp4文件，且不超过4096kb</div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" append-to-body>
              <img v-if="!endWith(dialogImageUrl,'.mp4')" style="width: 100%" :src="dialogImageUrl" alt="">
              <video v-else width="100%" controls>
                <source :src="dialogImageUrl" type="video/mp4">
              </video>
            </el-dialog>
          </el-form-item>
          <div style="color: red;margin-left:25%;margin-top: -25px;margin-bottom:5px;font-size: 10px;">
            推荐上传图片像素：宽*高是1080*590
          </div>
          <el-form-item label="内容" prop="content" style="width: 170%;">
            <richTextEdit :dataForm="dataForm" :dataKey="'content'" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="dataForm.detail"/>
          </el-form-item>
          <div>
            <el-button @click="cancel">取消</el-button>
            <el-button v-if="!dataForm.id" type="primary" @click="createData">确定</el-button>
            <el-button v-else type="primary" @click="updateData">确定</el-button>
          </div>
        </el-form>
      </el-col>
    </el-row>
</template>

<script>
import { uploadPath } from '@/api/base/storage'
import { create, update } from '@/api/apiHumanity'
import { getToken } from '@/utils/auth'
import richTextEdit from '@/components/richTextEdit'
export default {
  name: 'add',
  components: { richTextEdit },
  props: ['dataForm','cancel'],
  data(){
    return {
      types: ['旅行之选','风情民宿','媒体信息'],
      uploadPath,
      rules: rules,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs['dataForm'].clearValidate()
    })
  },
  methods: {
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.dataForm))
          formData.link = formData.link.map(item => item.url).join(';')
          create(formData).then(response => {
            this.$notify.success({
              title: '成功',
              message: '创建成功'
            })
            this.cancel()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.dataForm))
          formData.link = formData.link.map(item => item.url).join(';')
          update(formData).then(() => {
            this.$notify.success({
              title: '成功',
              message: '更新成功'
            })
            this.cancel()
          })
        }
      })
    },
    uploadUrl: function(response) {
      this.dataForm.link.push({
        url: response.data.url
      })
    },
    checkFileSize: function(file) {
      if (file.size > 1048576 * 4) {
        this.$message.error(`${file.name}文件大于4096KB，请选择小于1024KB大小的图片`)
        return false
      }
      return true
    },
    endWith(str, endStr) {
      const d = str.length - endStr.length
      return (d >= 0 && str.lastIndexOf(endStr) === d)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      for(let i = 0;i < this.dataForm.link.length;i++){
        if(file.url == this.dataForm.link[i].url){
          this.dataForm.link.splice(i,1)
          return
        }
      }
    },
    getVideoFirstImg(url) {
      console.log('video-' + url)
      const video = document.getElementById('video-' + url)
      const canvas = document.createElement('canvas')
      canvas.width = '300px'
      canvas.height = '300px'
      console.log(video)
      canvas.getContext('2d').drawImage(video, 0, 0, canvas.width,
        canvas.height)
      return canvas.toDataURL('image/png')
    }
  },
  computed: {
    headers() {
      return {
        'mbl_token': getToken()
      }
    }
  },
}


const rules = {
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '内容不能为空', trigger: 'blur' }
  ],
  graphicType: [
    { required: true, message: '必选', trigger: 'blur' }
  ],
  link: [{ required: true, message: '', trigger: 'blur' }]
}



</script>

<style scoped>

</style>
